import * as fs from 'fs';
import * as path from 'path';
import { app, dialog, BrowserWindow } from 'electron';
import log from 'electron-log';

// 文件操作结果接口
export interface FileOperationResult {
  success: boolean;
  data?: any;
  error?: string;
  filePath?: string;
}

interface ProgressCallback {
  (progress: number, total: number): void;
}

interface StreamOptions {
  chunkSize?: number;
  progressCallback?: ProgressCallback;
  highWaterMark?: number;
}

// 文件信息接口
export interface FileInfo {
  name: string;
  isFile: boolean;
  isDirectory: boolean;
  mtime: Date | null;
}

// 文件验证结果接口
export interface FileValidationResult {
  isValid: boolean;
  error?: string;
  normalizedPath?: string;
}

/**
 * 文件日志记录器
 */
class FileLogger {
  static info(message: string, ...args: any[]) {
    log.info(`[FileService] ${message}`, ...args);
  }

  static warn(message: string, ...args: any[]) {
    log.warn(`[FileService] ${message}`, ...args);
  }

  static error(message: string, ...args: any[]) {
    log.error(`[FileService] ${message}`, ...args);
  }

  static debug(message: string, ...args: any[]) {
    log.debug(`[FileService] ${message}`, ...args);
  }
}

interface ErrorRecoveryOptions {
  retryCount?: number;
  retryDelay?: number;
  fallbackPath?: string;
  createMissingDirectories?: boolean;
}

interface DetailedError {
  code: string;
  message: string;
  operation: string;
  filePath?: string;
  recoverable: boolean;
  suggestions: string[];
}

/**
 * 文件错误处理器
 */
class FileErrorHandler {
  private static readonly ERROR_CODES = {
    ENOENT: { message: '文件或目录不存在', recoverable: true },
    EACCES: { message: '权限不足', recoverable: false },
    EPERM: { message: '操作不被允许', recoverable: false },
    EEXIST: { message: '文件已存在', recoverable: true },
    ENOSPC: { message: '磁盘空间不足', recoverable: false },
    EMFILE: { message: '打开文件过多', recoverable: true },
    ENFILE: { message: '系统打开文件过多', recoverable: true },
    EISDIR: { message: '目标是目录而非文件', recoverable: false },
    ENOTDIR: { message: '路径中的组件不是目录', recoverable: false },
    EBUSY: { message: '文件正在使用中', recoverable: true },
    EROFS: { message: '只读文件系统', recoverable: false }
  };

  static analyzeError(error: any, operation: string, filePath?: string): DetailedError {
    const errorCode = error.code || 'UNKNOWN';
    const errorInfo = this.ERROR_CODES[errorCode as keyof typeof this.ERROR_CODES] || 
      { message: '未知错误', recoverable: false };

    const suggestions = this.generateSuggestions(errorCode, operation, filePath);

    return {
      code: errorCode,
      message: errorInfo.message,
      operation,
      filePath,
      recoverable: errorInfo.recoverable,
      suggestions
    };
  }

  private static generateSuggestions(errorCode: string, operation: string, filePath?: string): string[] {
    const suggestions: string[] = [];

    switch (errorCode) {
      case 'ENOENT':
        suggestions.push('检查文件路径是否正确');
        if (operation.includes('读取') || operation.includes('打开')) {
          suggestions.push('确认文件确实存在');
        } else {
          suggestions.push('尝试创建缺失的目录');
        }
        break;
      case 'EACCES':
      case 'EPERM':
        suggestions.push('检查文件权限设置');
        suggestions.push('尝试以管理员身份运行程序');
        suggestions.push('确认文件未被其他程序占用');
        break;
      case 'EEXIST':
        suggestions.push('使用不同的文件名');
        suggestions.push('删除现有文件后重试');
        suggestions.push('启用覆盖模式');
        break;
      case 'ENOSPC':
        suggestions.push('清理磁盘空间');
        suggestions.push('选择其他存储位置');
        break;
      case 'EMFILE':
      case 'ENFILE':
        suggestions.push('关闭不必要的文件句柄');
        suggestions.push('稍后重试操作');
        break;
      case 'EBUSY':
        suggestions.push('等待文件释放后重试');
        suggestions.push('关闭占用文件的程序');
        break;
      case 'EROFS':
        suggestions.push('选择可写的存储位置');
        suggestions.push('检查磁盘是否为只读模式');
        break;
    }

    return suggestions;
  }

  static handleFileError(error: any, operation: string, filePath?: string): FileOperationResult {
    const detailedError = this.analyzeError(error, operation, filePath);
    const contextMessage = filePath ? `文件路径: ${filePath}` : '';
    
    let errorMessage = `${operation}失败: ${detailedError.message}`;
    
    if (detailedError.suggestions.length > 0) {
      errorMessage += `\n建议: ${detailedError.suggestions.join('; ')}`;
    }
    
    FileLogger.error(errorMessage, contextMessage);
    
    return {
      success: false,
      error: errorMessage
    };
  }

  static async handleWithRetry<T>(
    operation: () => Promise<T>,
    options: ErrorRecoveryOptions = {}
  ): Promise<T> {
    const { retryCount = 3, retryDelay = 1000 } = options;
    let lastError: any;

    for (let attempt = 0; attempt <= retryCount; attempt++) {
      try {
        return await operation();
      } catch (error) {
        lastError = error;
        
        if (attempt === retryCount) {
          break;
        }

        const detailedError = this.analyzeError(error, '重试操作');
        if (!detailedError.recoverable) {
          break;
        }

        // 等待后重试
        await new Promise(resolve => setTimeout(resolve, retryDelay * (attempt + 1)));
      }
    }

    throw lastError;
  }

  static handlePathError(error: any, filePath: string): FileOperationResult {
    return this.handleFileError(error, '路径处理', filePath);
  }

  static handleReadError(error: any, filePath: string): FileOperationResult {
    return this.handleFileError(error, '读取文件', filePath);
  }

  static handleWriteError(error: any, filePath: string): FileOperationResult {
    return this.handleFileError(error, '写入文件', filePath);
  }

  static handleDeleteError(error: any, filePath: string): FileOperationResult {
    return this.handleFileError(error, '删除文件', filePath);
  }
}

/**
 * 文件服务类 - 统一管理所有文件操作
 */
export class FileService {
  private readonly pluginsDir: string;
  private requireAbsolutePath: boolean;

  constructor(pluginsDir: string, requireAbsolutePath: boolean = false) {
    this.pluginsDir = pluginsDir;
    this.requireAbsolutePath = requireAbsolutePath;
    FileLogger.info('FileService初始化完成', { pluginsDir });
  }

  /**
   * 验证文件路径安全性
   */
  private validateFilePath(filePath: string): FileValidationResult {
    try {
      // 检查基本输入
      if (!filePath || typeof filePath !== 'string') {
        return {
          isValid: false,
          error: '文件路径不能为空或必须为字符串类型'
        };
      }

      // 标准化路径
      const normalizedPath = path.normalize(filePath);
      
      // 检查路径长度限制
      if (normalizedPath.length > 260) { // Windows路径长度限制
        return {
          isValid: false,
          error: '文件路径过长，超过260字符限制'
        };
      }

      // 检查危险字符（Windows文件名不允许的字符）
      const dangerousChars = /[<>:"|?*\x00-\x1f]/;
      if (dangerousChars.test(path.basename(normalizedPath))) {
        return {
          isValid: false,
          error: '文件名包含非法字符'
        };
      }

      // 检查保留名称（Windows保留文件名）
      const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$/i;
      if (reservedNames.test(path.basename(normalizedPath, path.extname(normalizedPath)))) {
        return {
          isValid: false,
          error: '文件名使用了系统保留名称'
        };
      }
      
      // 检查路径遍历攻击
      if (normalizedPath.includes('..') || normalizedPath.includes('~')) {
        return {
          isValid: false,
          error: '不安全的文件路径：包含路径遍历字符或特殊字符'
        };
      }

      // 检查绝对路径（如果需要）
      if (this.requireAbsolutePath && !path.isAbsolute(normalizedPath)) {
        return {
          isValid: false,
          error: '文件路径必须是绝对路径'
        };
      }

      return {
        isValid: true,
        normalizedPath
      };
    } catch (error) {
      return {
        isValid: false,
        error: `路径验证失败: ${error}`
      };
    }
  }

  /**
   * 验证文件类型
   */
  private validateFileType(filePath: string, allowedExtensions?: string[]): { isValid: boolean; error?: string } {
    if (!allowedExtensions || allowedExtensions.length === 0) {
      return { isValid: true };
    }

    const ext = path.extname(filePath).toLowerCase();
    
    // 检查是否有扩展名
    if (!ext) {
      return {
        isValid: false,
        error: '文件必须有扩展名'
      };
    }

    // 检查扩展名是否在允许列表中
    const isAllowed = allowedExtensions.some(allowed => {
      const normalizedAllowed = allowed.startsWith('.') ? allowed.toLowerCase() : `.${allowed.toLowerCase()}`;
      return ext === normalizedAllowed;
    });

    if (!isAllowed) {
      return {
        isValid: false,
        error: `不支持的文件类型: ${ext}，允许的类型: ${allowedExtensions.join(', ')}`
      };
    }

    // 检查危险文件类型
    const dangerousExtensions = ['.exe', '.bat', '.cmd', '.com', '.scr', '.pif', '.vbs', '.js', '.jar', '.msi'];
    if (dangerousExtensions.includes(ext)) {
      return {
        isValid: false,
        error: `危险的文件类型: ${ext}`
      };
    }

    return { isValid: true };
  }

  /**
   * 确保目录存在
   */
  async ensureDirectoryExists(dirPath: string): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(dirPath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || dirPath;
      if (!fs.existsSync(normalizedPath)) {
        await fs.promises.mkdir(normalizedPath, { recursive: true });
        FileLogger.info('目录创建成功', normalizedPath);
      }
      
      return { success: true, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '创建目录', dirPath);
    }
  }

  /**
   * 读取目录内容
   */
  async readDirectory(dirPath: string): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(dirPath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || dirPath;
      const files = await fs.promises.readdir(normalizedPath, { withFileTypes: true });
      const fileInfos: FileInfo[] = [];

      for (const file of files) {
        const fileInfo: FileInfo = {
          name: file.name,
          isFile: file.isFile(),
          isDirectory: file.isDirectory(),
          mtime: null
        };

        // 获取文件修改时间
        if (fileInfo.isFile) {
          try {
            const filePath = path.join(normalizedPath, file.name);
            const stats = await fs.promises.stat(filePath);
            fileInfo.mtime = stats.mtime;
          } catch (error) {
            FileLogger.warn(`获取文件 ${file.name} 状态失败`, error);
          }
        }

        fileInfos.push(fileInfo);
      }

      FileLogger.info('目录读取成功', { dirPath: normalizedPath, fileCount: fileInfos.length });
      return { success: true, data: fileInfos };
    } catch (error) {
      return FileErrorHandler.handleReadError(error, dirPath);
    }
  }

  /**
   * 读取文件内容
   */
  async readFile(filePath: string, encoding: BufferEncoding = 'utf8'): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      const content = await fs.promises.readFile(normalizedPath, encoding);
      FileLogger.info('文件读取成功', normalizedPath);
      
      return { success: true, data: content, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleReadError(error, filePath);
    }
  }

  /**
   * 写入文件内容
   */
  async writeFile(filePath: string, content: string | Buffer, encoding: BufferEncoding = 'utf8'): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      
      // 使用重试机制写入文件
      await FileErrorHandler.handleWithRetry(async () => {
        // 确保目录存在
        const dir = path.dirname(normalizedPath);
        const dirResult = await this.ensureDirectoryExists(dir);
        if (!dirResult.success) {
          throw new Error(dirResult.error);
        }

        await fs.promises.writeFile(normalizedPath, content, encoding);
      }, { retryCount: 2, retryDelay: 500 });
      
      FileLogger.info('文件写入成功', normalizedPath);
      return { success: true, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleWriteError(error, filePath);
    }
  }

  /**
   * 删除文件
   */
  async deleteFile(filePath: string): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      await fs.promises.unlink(normalizedPath);
      FileLogger.info('文件删除成功', normalizedPath);
      
      return { success: true, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleDeleteError(error, filePath);
    }
  }

  /**
   * 保存复杂文件内容（支持多种格式）
   */
  async saveFile(filePath: string, fileContent: any): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      let buffer: Buffer;

      // 处理不同类型的文件内容
      if (Buffer.isBuffer(fileContent)) {
        buffer = fileContent;
      } else if (ArrayBuffer.isView(fileContent)) {
        buffer = Buffer.from(fileContent.buffer, fileContent.byteOffset, fileContent.byteLength);
      } else if (fileContent instanceof ArrayBuffer) {
        buffer = Buffer.from(fileContent);
      } else if (typeof fileContent === 'string') {
        buffer = Buffer.from(fileContent);
      } else if (fileContent && typeof fileContent === 'object') {
        // 处理序列化后的对象
        buffer = this.processObjectContent(fileContent);
      } else if (Array.isArray(fileContent)) {
        buffer = Buffer.from(fileContent);
      } else {
        throw new Error(`无法处理的文件内容类型: ${typeof fileContent}`);
      }

      if (!buffer) {
        throw new Error('无法创建有效的Buffer');
      }

      const normalizedPath = validation.normalizedPath || filePath;
      // 确保目录存在
      const dir = path.dirname(normalizedPath);
      const dirResult = await this.ensureDirectoryExists(dir);
      if (!dirResult.success) {
        return dirResult;
      }

      fs.writeFileSync(normalizedPath, buffer);
      FileLogger.info('复杂文件保存成功', { filePath: normalizedPath, size: buffer.length });
      
      return { success: true, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleWriteError(error, filePath);
    }
  }

  /**
   * 处理对象类型的文件内容
   */
  private processObjectContent(fileContent: any): Buffer {
    if (fileContent.data) {
      if (ArrayBuffer.isView(fileContent.data)) {
        return Buffer.from(fileContent.data.buffer, fileContent.data.byteOffset, fileContent.data.byteLength);
      } else if (fileContent.data instanceof ArrayBuffer) {
        return Buffer.from(fileContent.data);
      } else if (Array.isArray(fileContent.data)) {
        return Buffer.from(fileContent.data);
      }
    } else if (fileContent.buffer) {
      if (ArrayBuffer.isView(fileContent.buffer)) {
        return Buffer.from(fileContent.buffer.buffer, fileContent.buffer.byteOffset, fileContent.buffer.byteLength);
      } else if (fileContent.buffer instanceof ArrayBuffer) {
        return Buffer.from(fileContent.buffer);
      } else if (Array.isArray(fileContent.buffer)) {
        return Buffer.from(fileContent.buffer);
      }
    }
    
    throw new Error('无法识别的对象文件内容格式');
  }

  /**
   * 获取文件完整路径（处理上传文件）
   */
  async getFileFullPath(file: any): Promise<FileOperationResult> {
    try {
      // 验证文件对象 - 兼容HTML File对象
      if (!file || typeof file !== 'object' || !file.name || typeof file.arrayBuffer !== 'function') {
        return { success: false, error: '无效的文件对象: 缺少必要属性或方法' };
      }

      // 如果文件已有路径，直接返回
      if (file.path && typeof file.path === 'string') {
        const validation = this.validateFilePath(file.path);
        if (!validation.isValid) {
          return { success: false, error: validation.error };
        }
        const normalizedPath = validation.normalizedPath || file.path;
        return { success: true, filePath: normalizedPath };
      }

      // 检查HTML File对象的webkitRelativePath属性
      if (file.webkitRelativePath && typeof file.webkitRelativePath === 'string') {
        // 对于HTML File对象，我们返回文件名而不是完整路径
        // 因为浏览器安全限制不允许访问真实的文件系统路径
        FileLogger.info('HTML File对象检测到webkitRelativePath', { 
          name: file.name, 
          webkitRelativePath: file.webkitRelativePath 
        });
        return { success: true, filePath: file.name };
      }

      // 对于HTML File对象，直接返回文件名
      // 在Electron环境中，通常不需要创建临时文件
      FileLogger.info('HTML File对象处理', { 
        name: file.name, 
        size: file.size,
        type: file.type 
      });
      
      return { success: true, filePath: file.name };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '获取文件路径');
    }
  }

  /**
   * 获取应用路径
   */
  getAppPath(name: string): FileOperationResult {
    try {
      const appPath = app.getPath(name as any);
      return { success: true, filePath: appPath };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, `获取应用路径 (${name})`);
    }
  }

  /**
   * 获取桌面路径
   */
  getDesktopPath(): FileOperationResult {
    try {
      const desktopPath = app.getPath('desktop');
      return { success: true, filePath: desktopPath };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '获取桌面路径');
    }
  }

  /**
   * 打开文件
   */
  async openFile(filePath: string): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      const { shell } = require('electron');
      await shell.openPath(normalizedPath);
      FileLogger.info('文件打开成功', normalizedPath);
      
      return { success: true, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '打开文件', filePath);
    }
  }

  /**
   * 在文件夹中显示文件
   */
  async showItemInFolder(filePath: string): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      const { shell } = require('electron');
      shell.showItemInFolder(normalizedPath);
      FileLogger.info('文件夹中显示文件成功', normalizedPath);
      
      return { success: true, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '在文件夹中显示文件', filePath);
    }
  }

  /**
   * 显示文件选择对话框
   */
  async showOpenDialog(mainWindow: BrowserWindow | null, options: any): Promise<FileOperationResult> {
    try {
      // 不传递mainWindow参数，让文件对话框独立显示，避免主窗口被激活
      const result = await dialog.showOpenDialog(options);
      FileLogger.info('文件选择对话框完成', { canceled: result.canceled, fileCount: result.filePaths?.length });
      
      return { success: true, data: result };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '文件选择对话框');
    }
  }

  /**
   * 获取Word模板路径
   */
  getWordTemplatePath(pluginName: string): FileOperationResult {
    try {
      const templatePath = path.join(this.pluginsDir, pluginName, `${pluginName}.docx`);
      const validation = this.validateFilePath(templatePath);
      
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || templatePath;
      return { success: true, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '获取Word模板路径');
    }
  }

  /**
   * 保存Word文件到桌面
   */
  async saveWordFile(buffer: Buffer, filename: string): Promise<FileOperationResult> {
    try {
      const desktopResult = this.getDesktopPath();
      if (!desktopResult.success) {
        return desktopResult;
      }

      const filePath = path.join(desktopResult.filePath!, filename);
      const validation = this.validateFilePath(filePath);
      
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      // 验证文件类型
      const typeValidation = this.validateFileType(normalizedPath, ['.docx', '.doc']);
      if (!typeValidation.isValid) {
        return { success: false, error: typeValidation.error || '不支持的Word文件格式' };
      }

      fs.writeFileSync(normalizedPath, Buffer.from(buffer));
      FileLogger.info('Word文件保存成功', normalizedPath);
      
      return { success: true, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleWriteError(error, filename);
    }
  }

  /**
   * 大文件流式读取
   */
  async readFileStream(filePath: string, options: StreamOptions = {}): Promise<FileOperationResult> {
    try {
      // 验证文件路径
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      const { chunkSize = 64 * 1024, progressCallback, highWaterMark = 16 * 1024 } = options;

      // 检查文件是否存在
      if (!fs.existsSync(normalizedPath)) {
        return { success: false, error: '文件不存在' };
      }

      // 获取文件大小
      const stats = await fs.promises.stat(normalizedPath);
      const fileSize = stats.size;
      
      // 创建可读流
      const readStream = fs.createReadStream(normalizedPath, { 
        highWaterMark
        // 不设置encoding，默认返回Buffer
      });

      let bytesRead = 0;

      // 添加进度跟踪
      if (progressCallback) {
        readStream.on('data', (chunk: string | Buffer) => {
          const chunkSize = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk);
          bytesRead += chunkSize;
          progressCallback(bytesRead, fileSize);
        });
      }

      FileLogger.info('文件流创建成功', { filePath: normalizedPath, fileSize });
      return { success: true, data: readStream, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleReadError(error, filePath);
    }
  }

  /**
   * 大文件流式写入
   */
  async writeFileStream(filePath: string, options: StreamOptions = {}): Promise<FileOperationResult> {
    try {
      // 验证文件路径
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      const { highWaterMark = 16 * 1024, progressCallback } = options;

      // 确保目录存在
      const dir = path.dirname(normalizedPath);
      const dirResult = await this.ensureDirectoryExists(dir);
      if (!dirResult.success) {
        return { success: false, error: dirResult.error };
      }

      // 创建可写流
      const writeStream = fs.createWriteStream(normalizedPath, { 
        highWaterMark,
        flags: 'w'
      });

      let bytesWritten = 0;

      // 添加进度跟踪
      if (progressCallback) {
        writeStream.on('write', (chunk: Buffer) => {
          bytesWritten += chunk.length;
          progressCallback(bytesWritten, bytesWritten); // 写入时无法预知总大小
        });
      }

      FileLogger.info('写入流创建成功', { filePath: normalizedPath });
      return { success: true, data: writeStream, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleWriteError(error, filePath);
    }
  }

  /**
   * 大文件复制（带进度）
   */
  async copyLargeFile(sourcePath: string, destPath: string, progressCallback?: ProgressCallback): Promise<FileOperationResult> {
    try {
      // 验证源文件路径
      const sourceValidation = this.validateFilePath(sourcePath);
      if (!sourceValidation.isValid) {
        return { success: false, error: `源文件路径无效: ${sourceValidation.error}` };
      }

      // 验证目标文件路径
      const destValidation = this.validateFilePath(destPath);
      if (!destValidation.isValid) {
        return { success: false, error: `目标文件路径无效: ${destValidation.error}` };
      }

      const normalizedSource = sourceValidation.normalizedPath || sourcePath;
      const normalizedDest = destValidation.normalizedPath || destPath;

      // 检查源文件是否存在
      if (!fs.existsSync(normalizedSource)) {
        return { success: false, error: '源文件不存在' };
      }

      // 获取文件大小
      const stats = await fs.promises.stat(normalizedSource);
      const fileSize = stats.size;

      // 确保目标目录存在
      const destDir = path.dirname(normalizedDest);
      const dirResult = await this.ensureDirectoryExists(destDir);
      if (!dirResult.success) {
        return { success: false, error: dirResult.error };
      }

      return new Promise((resolve) => {
        const readStream = fs.createReadStream(normalizedSource);
        const writeStream = fs.createWriteStream(normalizedDest);
        
        let copiedBytes = 0;

        readStream.on('data', (chunk: string | Buffer) => {
          const chunkSize = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk);
          copiedBytes += chunkSize;
          if (progressCallback) {
            progressCallback(copiedBytes, fileSize);
          }
        });

        readStream.on('error', (error) => {
          resolve(FileErrorHandler.handleReadError(error, sourcePath));
        });

        writeStream.on('error', (error) => {
          resolve(FileErrorHandler.handleWriteError(error, destPath));
        });

        writeStream.on('finish', () => {
          FileLogger.info('大文件复制完成', { 
            source: normalizedSource, 
            dest: normalizedDest, 
            size: fileSize 
          });
          resolve({ success: true, filePath: normalizedDest });
        });

        readStream.pipe(writeStream);
      });
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '复制大文件');
    }
  }

  /**
   * 检查文件大小
   */
  async getFileSize(filePath: string): Promise<FileOperationResult> {
    try {
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return { success: false, error: validation.error };
      }

      const normalizedPath = validation.normalizedPath || filePath;
      const stats = await fs.promises.stat(normalizedPath);
      
      return { success: true, data: stats.size, filePath: normalizedPath };
    } catch (error) {
      return FileErrorHandler.handleFileError(error, '获取文件大小', filePath);
    }
  }

  /**
   * 判断是否为大文件（超过指定大小）
   */
  async isLargeFile(filePath: string, threshold: number = 10 * 1024 * 1024): Promise<boolean> {
    const sizeResult = await this.getFileSize(filePath);
    return sizeResult.success && (sizeResult.data || 0) > threshold;
  }

  /**
   * 检查文件是否存在
   */
  async checkFileExists(filePath: string): Promise<boolean> {
    try {
      const validation = this.validateFilePath(filePath);
      if (!validation.isValid) {
        return false;
      }

      const normalizedPath = validation.normalizedPath || filePath;
      await fs.promises.access(normalizedPath, fs.constants.F_OK);
      return true;
    } catch (error) {
      return false;
    }
  }
}